using System.Linq;
using AspNetCoreMVC.Db;
using AspNetCoreMVC.IRepository;
using AspNetCoreMVC.Models;
using Microsoft.EntityFrameworkCore;

namespace AspNetCoreMVC.EfRepository
{
    public class EfRepository<T> : IRepository<T> where T : Bass
    {
        private readonly AspNetCoreMVC.Db.mvcDemoDb _db;
        private readonly DbSet<T> _table;

        public EfRepository(){
            _db=new mvcDemoDb();
            _table=_db.Set<T>();
        }
        public IQueryable<T> table {get{return _table.AsQueryable();}}

        public void Delete(int id)
        {
            var entity =_table.Where(x=>x.Id==id).FirstOrDefault();
            if (entity==null)
            {
                throw new System.Exception();
            }

            entity.IsDeleted=true;
            entity.UpdatedTime=System.DateTime.Now;

            _table.Remove(entity);
            _db.SaveChanges();
        }

        public T GetByid(int id)
        {
           var entity = _table.Where(x=>x.Id==id).FirstOrDefault();
           return entity;

        }

        public void Insert(T entity)
        {
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
           if (entity==null)
           {
               throw new System.Exception();
           }
           if(entity.Id==0){
               throw new System.Exception();
           }
           _table.Update(entity);
           _db.SaveChanges();
        }
    }
}